<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? $t('page.system.user.edit') : $t('page.system.user.add')"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item :label="$t('page.system.user.username')" prop="username">
        <el-input
          v-model="form.username"
          :placeholder="$t('page.system.user.form.usernameRequired')"
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item v-if="!isEdit" :label="'密码'" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
        />
      </el-form-item>

      <el-form-item :label="$t('page.system.user.realName')" prop="realName">
        <el-input
          v-model="form.realName"
          :placeholder="$t('page.system.user.form.realNameRequired')"
        />
      </el-form-item>

      <el-form-item :label="$t('page.system.user.nickName')" prop="nickName">
        <el-input
          v-model="form.nickName"
          placeholder="请输入昵称"
        />
      </el-form-item>

      <el-form-item :label="$t('page.system.user.gender')" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio :label="1">{{ $t('page.system.user.male') }}</el-radio>
          <el-radio :label="0">{{ $t('page.system.user.female') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('page.system.user.phone')" prop="phone">
        <el-input
          v-model="form.phone"
          :placeholder="$t('page.system.user.form.phoneRequired')"
        />
      </el-form-item>

      <el-form-item :label="$t('page.system.user.birthday')" prop="birthday">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          placeholder="请选择生日"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item :label="$t('page.system.user.role')" prop="roleId">
        <el-select
          v-model="form.roleId"
          :placeholder="$t('page.system.user.form.roleRequired')"
          style="width: 100%"
        >
          <el-option
            v-for="role in roleOptions"
            :key="role.id"
            :label="role.name"
            :value="role.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('page.system.user.status')" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">{{ $t('page.system.user.normal') }}</el-radio>
          <el-radio :label="0">{{ $t('page.system.user.disabled') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ $t('page.system.user.cancel') }}</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ $t('page.system.user.save') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import {
  ElButton,
  ElDatePicker,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElOption,
  ElRadio,
  ElRadioGroup,
  ElSelect,
  type FormInstance,
  type FormRules,
} from 'element-plus';

import type { UserDetail, UserFormData } from '#/api/system/user';
import { createUserApi, updateUserApi } from '#/api/system/user';
import { getAllRolesApi } from '#/api/system/role';
import { $t } from '#/locales';

interface Props {
  visible: boolean;
  formData?: Partial<UserDetail>;
  isEdit: boolean;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'submit'): void;
}

interface RoleOption {
  id: number;
  name: string;
  roleKey: string;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const loading = ref(false);
const roleOptions = ref<RoleOption[]>([]);

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const form = reactive<UserFormData>({
  username: '',
  password: '',
  realName: '',
  nickName: '',
  gender: 0,
  birthday: null,
  avatar: '',
  phone: '',
  status: 1,
  roleId: 0,
});

const rules: FormRules = {
  username: [
    { required: true, message: $t('page.system.user.form.usernameRequired'), trigger: 'blur' },
    { min: 2, max: 20, message: $t('page.system.user.form.usernameLength'), trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' },
  ],
  realName: [
    { required: true, message: $t('page.system.user.form.realNameRequired'), trigger: 'blur' },
  ],
  phone: [
    { required: true, message: $t('page.system.user.form.phoneRequired'), trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: $t('page.system.user.form.phonePattern'), trigger: 'blur' },
  ],
  roleId: [
    { required: true, message: $t('page.system.user.form.roleRequired'), trigger: 'change' },
  ],
  status: [
    { required: true, message: $t('page.system.user.form.statusRequired'), trigger: 'change' },
  ],
};

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData && props.visible) {
      Object.assign(form, {
        id: newData.id,
        username: newData.username || '',
        realName: newData.realName || '',
        nickName: newData.nickName || '',
        gender: newData.gender ?? 0,
        birthday: newData.birthday || '',
        avatar: newData.avatar || '',
        phone: newData.phone || '',
        status: newData.status ?? 1,
        roleId: newData.role?.id || 0,
      });
    }
  },
  { immediate: true }
);

// 获取角色列表
const getRoleList = async () => {
  try {
    const response = await getAllRolesApi();
    roleOptions.value = response || [];
  } catch (error) {
    console.error('获取角色列表失败:', error);
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    username: '',
    password: '',
    realName: '',
    nickName: '',
    gender: 0,
    birthday: '',
    avatar: '',
    phone: '',
    status: 1,
    roleId: 0,
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;
    
    const submitData = { ...form };
    if (props.isEdit) {
      delete submitData.password; // 编辑时不传密码
    }

    const response = props.isEdit 
      ? await updateUserApi(submitData)
      : await createUserApi(submitData);

    if (response.data.code === 200) {
      ElMessage.success(
        props.isEdit 
          ? $t('page.system.user.message.updateSuccess')
          : $t('page.system.user.message.createSuccess')
      );
      emit('submit');
      handleClose();
    }
  } catch (error) {
    console.error('保存用户失败:', error);
    ElMessage.error('保存用户失败');
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  resetForm();
  emit('update:visible', false);
};

onMounted(() => {
  getRoleList();
});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 
 